import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd/message';

import {UsedStoreZservice} from '../used-store-zservice';
import {PermissionService} from '../../../service/permission.service';

@Component({
  selector: 'app-used-location-manage',
  templateUrl: './used-location-manage.component.html',
  styleUrls: ['./used-location-manage.component.scss']
})
export class UsedLocationManageComponent implements OnInit {

  seachParams: any = {
    num: '',
    status: '',
    type: ''
  };
  typeOptions: any = [];
  typeSelected: any = [];

  tableParams: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0
  };
  tableData: any = [];

  // Modal
  isVisible: boolean = false;
  validateForm!: FormGroup;
  updateItem: any = {};

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private services: UsedStoreZservice,
    public permissionService: PermissionService
  ) {
  }

  ngOnInit(): void {
    this.getDictListData();
    this.validateForm = this.fb.group({
      num: ['', [Validators.required]],
      name: ['', [Validators.required]],
      status: ['0', [Validators.required]],
      type: ['', [Validators.required]],
      remarks: ['', [Validators.required]],
    });

    this.loadTable();
  }

  // 查询类型list
  async getDictListData() {
    const res: any = await this.services.dictListData('machine_storage_location_type');
    if (res.code == 0) {
      const {list} = res.data || {};
      this.typeOptions = list || [];
    } else {
      this.typeOptions = [];
    }
  }

  async loadTable() {
    try {
      let params = {
        ...this.seachParams,
        page: this.tableParams.page,
        pageSize: this.tableParams.pageSize
      };
      const res: any = await this.services.recycleLibraryList(params);

      if (res.code == 0) {
        const {records, total} = res.data || {};
        this.tableData = records || [];
        this.tableParams.total = total || 0;
      } else {
        this.message.error(res.message);
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  seachData() {
    this.tableParams.page = 1;
    this.loadTable();
  }

  resetData() {
    for (let key in this.seachParams) {
      this.seachParams[key] = '';
    }
    this.typeSelected = [];

    this.tableParams.page = 1;
    this.loadTable();
  }

  typeChange(event: any) {
    this.seachParams.type = event.join(',');
  }

  showModal(item?: any) {
    if (item) {
      this.updateItem = item;
      this.validateForm.patchValue({
        num: item.num,
        name: item.name,
        status: String(item.status),
        type: String(item.type),
        remarks: item.remarks,
      });
    } else {
      this.updateItem = {};
      this.validateForm.get('status')?.setValue('0');
    }
    this.isVisible = true;
  }

  handleCancel() {
    this.isVisible = false;
    this.validateForm.reset();
  }

  submitForm() {
    if (this.validateForm.valid) {
      this.subFormInterface();
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({onlySelf: true});
        }
      });
    }
  }

  async subFormInterface() {
    let params = {
      ...this.validateForm.value
    };
    let res: any;

    if (this.updateItem.id) {
      // 编辑
      params.id = this.updateItem.id;
      res = await this.services.updateRecycleLibrary(params);
    } else {
      // 新增
      res = await this.services.saveRecycleLibrary(params);
    }

    if (res.code == 0) {
      this.message.success('操作成功');
      this.isVisible = false;
      this.loadTable();
    } else {
      this.message.error(res.message);
    }
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }

  // 页数改变时的回调函数
  onPageSizeChange(sizeNum: number) {
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  // 类型名
  filterTypeName(type: any) {
    let tempObj: any = this.typeOptions.find((item: any) => {
      return item.content == type;
    });
    return tempObj?.name || '-';
  }
}
